/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package com.xinyue.server.framework.server.websocket;


import com.xinyue.server.framework.handler.GameServerEncryptService;
import com.xinyue.server.framework.message.GameMessagePackage;
import com.xinyue.server.framework.server.common.GameMessageCodecService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

/**
 * @author 王广帅
 * @since 2021/5/30 19:33
 */
public class WebSocketDecoderHandler extends SimpleChannelInboundHandler<Object> {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketDecoderHandler.class);

    /**
     * 读取连接消息
     *
     * @param ctx 连接管理类
     * @param msg 网络消息
     */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof TextWebSocketFrame) {
            try {
                String receiveMsg = ((TextWebSocketFrame) msg).text();
                byte[] data = Base64Utils.decodeFromString(receiveMsg);
                ByteBuf byteBuf = Unpooled.wrappedBuffer(data);
                byte[] aesKey = GameServerEncryptService.getAesKey(ctx.channel());
                GameMessagePackage gameMessagePackage = GameMessageCodecService.decode(byteBuf, aesKey);
                ctx.fireChannelRead(gameMessagePackage);
            } catch (Throwable e) {
                logger.info("解析客户端请求异常，断开连接");
                ctx.fireExceptionCaught(e);
                ctx.close();
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    }

}
